package cc.vv.btpartyjob.jnimodule.activity

import android.content.Intent
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.webkit.JavascriptInterface
import cc.vv.baselibrary.util.LKAppUtil
import cc.vv.baselibrary.util.LKJsonUtil
import cc.vv.baselibrary.util.UserInfoManageUtil
import cc.vv.baselibrary.view.BaseTopBarView
import cc.vv.baselibrary.view.BtWebView
import cc.vv.btpartyjob.jnimodule.binder.BaseBinder
import cc.vv.btpartyjob.jnimodule.globle.IntentJniKey
import cc.vv.btpartyjob.jnimodule.moudel.bean.H5OrgBean
import cc.vv.btpartyjob.jnimodule.server.JniDataServer
import cc.vv.btpartyjob.jnimodule.server.JniStartActivity
import cc.vv.btpartyjob.jnimodule.server.ResourceChooseServer
import cc.vv.btpartyjob.partyservice.delegate.WebDetailActivityDelegate
import cc.vv.mvp.activity.BaseActivityMVP
import cc.vv.mvp.binder.BaseDataBinder
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import org.json.JSONObject

/**
 * Web详情页
 * Created by Chen.qi on 2018/10/30.
 */
class WebDetailActivity : BaseActivityMVP<WebDetailActivityDelegate>() {

    private var mJsInterface: JSInterface? = null

    private var webView: BtWebView? = null

    private var idNew: String = "123456"


    override fun initData() {
        viewDelegate?.initWebClient(MyWebViewClient(), MyWebCromeClient())

        var title: String? = null
        var url: String? = null
        try {
            title = intent.getStringExtra(IntentJniKey.INTENT_KEY_WEB_TITLE)
        } catch (e: Exception) {
        }

        try {
            url = intent.getStringExtra(IntentJniKey.INTENT_KEY_WEB_URL)

            Log.e("chen", "result==" + url)

        } catch (e: Exception) {
        }

        if (TextUtils.isEmpty(title)) {
            viewDelegate?.setTopBarTitle("详情")
        } else {
            viewDelegate?.setTopBarTitle(title)
        }
        viewDelegate?.setRightPic("0")

        if (!TextUtils.isEmpty(url)) {
            viewDelegate?.setWebViewUrl(url!!)
        }
        webView = viewDelegate.getWebView()
        mJsInterface = JSInterface()
        webView?.addJavascriptInterface(mJsInterface, "BenchJSInterface")
    }

    override fun bindEvenListener() {
        viewDelegate?.setTitleBackBtnOnClick(object : BaseTopBarView.EventInterface {
            //返回
            override fun leftOnClick() {
                finish()
            }

            override fun leftCloseClick() {}
            override fun rightOnClick() {
                if (clickType == "1") {
                    ResourceChooseServer.getWheelerWayDialog(this@WebDetailActivity,
                            "选择时间", handler, 11, JniDataServer.getYearData(), 2)
                } else if (clickType == "2") {
                    JniStartActivity.startIntentOrganActivity(this@WebDetailActivity, orgType, orgChooseType,
                            100)
                } else if (clickType == "3") {
                    handler.sendEmptyMessage(5)
                }
            }
        })


    }

    override fun getDelegateClass(): Class<WebDetailActivityDelegate> {
        return WebDetailActivityDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return BaseBinder()
    }


    /**
     * MyWebViewClient
     */
    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl(url)
            return true
        }

        override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {}

        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, error: SslError?) {
            //接受所有证书
            handler.proceed()
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
        }
    }


    private inner class MyWebCromeClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
//            val proView = getView<WebProgressView>(R.id.pv_awJni_progressBar)
            if (newProgress == 100) {
                //加载完毕进度条消失
//                proView?.visibility = View.GONE
                loading.closeLoading()
            } else {
                //更新进度
//                proView?.setProgress(newProgress)
                if (!loading.isShowing) {
                    loading.showLoading()
                }
            }
        }
    }


    override fun onHandleMsg(msg: Message?) {
        super.onHandleMsg(msg)
        when (msg?.what) {
            5 -> {
                val newJs = timeJs?.replace("->path<-", idNew)
                webView?.loadUrl(newJs)
            }
            9 -> {
                viewDelegate?.setTopBarTitle(titleContent)
            }

            10 -> {
                viewDelegate?.setRightPic(clickType)
            }
            11 -> {
                val wayString: String = msg.obj as String
                val newJs = timeJs?.replace("->path<-", wayString.substring(0, wayString.length - 1))
                webView?.loadUrl(newJs)
            }
        }
    }


    /**
     * title内容
     */
    private var titleContent: String? = null

    /**
     * 点击类型
     * 0:隐藏右边半年
     * 1：时间选择
     * 2：组织选择
     */
    private var clickType: String? = null

    /**
     * 时间选择的js回调
     */
    private var timeJs: String? = null

    /**
     * 组织结构js回调
     */
    private var orgJs: String? = null


    /**
     * orgType 组织结构显示类型
     */
    private var orgType: Int = 0

    /**
     * orgChooseType 组织结构选择类型
     */
    private var orgChooseType: Int = 0

    /**
     * Js调用Android代码，点击H5网页的首页的"关闭"按钮调用Android代码关闭展示webView的Activity
     */
    private inner class JSInterface {
        /**
         * 设置标题Js回调
         */
        @JavascriptInterface
        fun setTitle(title: String) {
            titleContent = title
            handler.sendEmptyMessage(9)
        }

        /**
         * 设置右边图标
         * 0::隐藏
         * 1::显示固定图标
         */
        @JavascriptInterface
        fun setRightImage(typeJson: String?, js: String?) {
            timeJs = js
            orgJs = js
            val click: String?
            try {
                val json = JSONObject(typeJson)
                click = json.getString("clickType")
                clickType = click
                val type = json.getString("type")
                val chooseType = json.getString("chooseType")
                if (LKAppUtil.getInstance().isNumeric(type)) {
                    orgType = type.toInt()
                }
                if (LKAppUtil.getInstance().isNumeric(chooseType)) {
                    orgChooseType = chooseType.toInt()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
//            val msg = Message()
//            msg.what = 10
//            msg.obj = orgType
//            handler.sendMessage(msg)
            handler.sendEmptyMessage(10)
        }


        /**
         * 获取用户信息
         */
        @JavascriptInterface
        fun getUserToken(js: String) {
            val userInfo = UserInfoManageUtil.getUserInfo()
            val newJs = js.replace("->path<-", LKJsonUtil.objConversionJsonString(userInfo))
            webView?.loadUrl(newJs)

        }

        /**
         * 选择组织机构
         */
        @JavascriptInterface
        fun chooseOrg(json_: String, js: String) {
            val json = JSONObject(json_)
            val type: String?
            orgJs = js
            try {
                type = json.getString("type")
                val chooseType = json.getString("chooseType")
                var orgType = 0
                var orgChooseType = 0
                if (LKAppUtil.getInstance().isNumeric(type)) {
                    orgType = type.toInt()
                }
                if (LKAppUtil.getInstance().isNumeric(chooseType)) {
                    orgChooseType = chooseType.toInt()
                }

                if (orgType == 10) {
                    val intent = Intent()
                    intent.setClass(this@WebDetailActivity, DangZuZhiOrganizationActivity::class.java)
                    startActivityForResult(intent, 102)
                } else {
                    JniStartActivity.startIntentOrganActivity(this@WebDetailActivity, orgType, orgChooseType,
                            100)
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (null == data) {
            return
        }
        if (requestCode == 100 && resultCode == 101) {
            val orgId = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_ID)
            val orgName = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_NAME)
            val orgType = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_TYPE)
            val org = H5OrgBean(orgId, orgName, orgType)
            val newJs = orgJs?.replace("->path<-",
                    LKJsonUtil.objConversionJsonString(org))
            webView?.loadUrl(newJs)
        } else if (requestCode == 102 && resultCode == 101) {
            val branchId = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_ID)
            val branchName = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_NAME)
            val branchType = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_TYPE)
            val org = H5OrgBean(branchId, branchName, branchType)
            val newJs = orgJs?.replace("->path<-",
                    LKJsonUtil.objConversionJsonString(org))
             webView?.loadUrl(newJs)
        }
    }

}